<template>
  <view class="add-address-container">
    <!-- 顶部导航栏 -->
    <view class="custom-nav">
      <image class="nav-back-icon" src="/static/icon/back.png" mode="aspectFit" @click="goBack" />
      <view class="nav-back"></view>
      <text class="nav-title">编辑地址</text>
      <view class="nav-placeholder"></view>
    </view>

    <!-- 三级联动表单 -->
    <form @submit="handleSubmit">
      <!-- 省份选择 -->
      <view class="form-item">
        <text class="label">省份</text>
        <picker 
          mode="selector" 
          :range="provinces" 
          :value="selectedProvinceIndex" 
          @change="onProvinceChange"
        >
          <view class="picker">
            {{ selectedProvinceName || '请选择省份' }}
          </view>
        </picker>
      </view>

      <!-- 城市选择 -->
      <view class="form-item" v-if="cities.length > 0">
        <text class="label">城市</text>
        <picker 
          mode="selector" 
          :range="cities" 
          :value="selectedCityIndex" 
          @change="onCityChange"
        >
          <view class="picker">
            {{ selectedCityName || '请选择城市' }}
          </view>
        </picker>
      </view>

      <!-- 区县选择 -->
      <view class="form-item" v-if="districts.length > 0">
        <text class="label">区县</text>
        <picker 
          mode="selector" 
          :range="districts" 
          :value="selectedDistrictIndex" 
          @change="onDistrictChange"
        >
          <view class="picker">
            {{ selectedDistrictName || '请选择区县' }}
          </view>
        </picker>
      </view>

      <!-- 详细地址输入 -->
      <view class="form-item">
        <text class="label">详细地址</text>
        <input 
          v-model="formData.detailed" 
          placeholder="请输入详细地址（如：光华路1号）"
          required
          class="input"
        />
      </view>

      <!-- 提交按钮 -->
      <button type="primary" form-type="submit" class="submit-btn">保存修改</button>
    </form>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getAddressDetail, updateAddress } from '@/api/address';
import areaData from '@/utils/china-area.json'; 

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};


const provinces = ref(areaData.provinces.map(p => p.name));
const cities = ref<string[]>([]);
const districts = ref<string[]>([]);

// 选中索引（需根据地址详情初始化）
const selectedProvinceIndex = ref(-1);
const selectedCityIndex = ref(-1);
const selectedDistrictIndex = ref(-1);

// 选中名称（绑定到表单）
const selectedProvinceName = ref('');
const selectedCityName = ref('');
const selectedDistrictName = ref('');

// 表单数据（包含地址ID）
const formData = ref({
  province: '',
  city: '',
  area: '',
  detailed: ''
});
const id = ref('');

// 生命周期：页面加载时获取地址详情并初始化表单
onMounted(async () => {
    const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const addid = currentPage.options.id;
  if (!addid) {
    uni.showToast({ title: '地址ID缺失', icon: 'none' });
    return;
  }
  id.value = addid;

  // 获取地址详情
  const res = await getAddressDetail(addid);
  if (res.code === 200) {
    const { province, city, area, detailed } = res.data;
    
    // 初始化省份选择
    const provinceIndex = areaData.provinces.findIndex(p => p.name === province);
    if (provinceIndex !== -1) {
      selectedProvinceIndex.value = provinceIndex;
      selectedProvinceName.value = province;
      
      // 初始化城市选择
      const cityList = areaData.provinces[provinceIndex].cities;
      const cityIndex = cityList.findIndex(c => c.name === city);
      if (cityIndex !== -1) {
        cities.value = cityList.map(c => c.name);
        selectedCityIndex.value = cityIndex;
        selectedCityName.value = city;
        
        // 初始化区县选择
        const districtList = cityList[cityIndex].districts;
        const districtIndex = districtList.findIndex(d => d === area);
        if (districtIndex !== -1) {
          districts.value = districtList;
          selectedDistrictIndex.value = districtIndex;
          selectedDistrictName.value = area;
        }
      }
    }

    // 初始化详细地址
    formData.value.detailed = detailed;
  }
});


const onProvinceChange = (e: any) => {
  const index = e.detail.value;
  selectedProvinceIndex.value = index;
  selectedProvinceName.value = provinces.value[index];
  
  const selectedProvince = areaData.provinces[index];
  cities.value = selectedProvince.cities.map(c => c.name);
  selectedCityIndex.value = -1;
  selectedCityName.value = '';
  districts.value = [];
  selectedDistrictIndex.value = -1;
  selectedDistrictName.value = '';
};


const onCityChange = (e: any) => {
  const index = e.detail.value;
  selectedCityIndex.value = index;
  selectedCityName.value = cities.value[index];
  
  const selectedProvince = areaData.provinces[selectedProvinceIndex.value];
  const selectedCity = selectedProvince.cities[index];
  districts.value = selectedCity.districts;
  selectedDistrictIndex.value = -1;
  selectedDistrictName.value = '';
};


const onDistrictChange = (e: any) => {
  const index = e.detail.value;
  selectedDistrictIndex.value = index;
  selectedDistrictName.value = districts.value[index];
};

// 提交修改
const handleSubmit = async () => {
  // 同步三级联动数据到表单
  formData.value.province = selectedProvinceName.value;
  formData.value.city = selectedCityName.value;
  formData.value.area = selectedDistrictName.value;

  // 校验
  if (!formData.value.province || !formData.value.city || !formData.value.area) {
    uni.showToast({ title: '请完整选择省市区', icon: 'none' });
    return;
  }

  try {
    const res = await updateAddress(id.value,formData.value);
    console.log(res)
    if (res.code === 200) { 
      uni.showToast({ title: '地址修改成功', icon: 'success' });
      uni.navigateBack(); 
    } else {
      uni.showToast({ title: res.data?.message || '地址修改失败', icon: 'none' });
    }
  } catch (error) {
    const msg = error instanceof Error ? error.message : '网络请求失败';
    uni.showToast({ title: `请求失败：${msg}`, icon: 'none' });
  }
};
</script>

<style lang="scss" scoped>
.add-address-container {
  padding: 30rpx;

  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    padding: 20rpx;
    background: #fff;
    border-radius: 12rpx;

    .label {
      width: 160rpx;
      font-size: 30rpx;
      color: #333;
    }

    .input {
      flex: 1;
      font-size: 30rpx;
      padding: 10rpx 20rpx;
    }
  }

  .submit-btn {
    margin-top: 50rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
    background: #007aff;
    color: #fff;
    border-radius: 12rpx;
    border: none;
  }
}

/* 新增顶部导航栏样式（与index.vue保持一致） */
.custom-nav {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  margin-bottom: 20rpx;
  background: #fff;

  .nav-back-icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 10rpx;
  }

  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }

  .nav-placeholder {
    width: 60rpx;
  }
}

/* 调整选择器样式 */
.picker {
  flex: 1;
  font-size: 30rpx;
  padding: 10rpx 20rpx;
  color: #666;
}
</style>